<template>
  <div>
    <van-nav-bar title="注册账号" left-arrow @click-left="onClickLeft" />
    <h1>欢迎━(*｀∀´*)ノ亻!注册</h1>
    <van-form @submit="onSubmit">
      <van-cell-group>
        <van-field
          v-model="username"
          name="用户名"
          label="用户名"
          left-icon="manager"
          placeholder="请输入手机号"
          :rules="rules.username"
          autocomplete
        />
        <van-field
          v-model="password1"
          clearable
          name="密码"
          label="密码"
          type="password"
          left-icon="lock"
          placeholder="密码"
          :rules="rules.password"
          autocomplete
        />
        <van-field
          v-model="password2"
          clearable
          name="确认密码"
          label="确认密码"
          type="password"
          left-icon="lock"
          placeholder="确认密码"
          autocomplete
          :rules="[
            { required: true, message: '请填写密码' },
            { validator, message: '两次密码不一致' },
            rules.password
          ]"
        />
      </van-cell-group>
      <van-button
        round
        type="info"
        size="large"
        native-type="submit"
        :disabled="isLoading"
        :loading="isLoading"
        loading-text="注册中"
      >
        立即注册
      </van-button>
    </van-form>
  </div>
</template>

<script>
// 导入注册函数
import { userReg } from '@/api/register'
import { mapMutations } from 'vuex'
export default {
  data() {
    return {
      username: '',
      password1: '',
      password2: '',
      isLoading: false,
      rules: {
        username: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误'
          }
        ],
        password: [{ required: true, message: '密码不能为空' }]
      }
    }
  },

  methods: {
    ...mapMutations('user', ['setTokens']),
    async onSubmit() {
      this.isLoading = true
      try {
        const {
          data: { errmsg, errno, data }
        } = await userReg(this.username, this.password2)
        this.$toast.success(errmsg)
        if (errno === 0) {
          // 注册成功后跳转到首页
          this.setTokens(data.token)
          this.$router.push('/home')
        }
      } catch (e) {
        console.log(e)
        this.$toast.fail('注册失败')
      }
      this.isLoading = false
    },
    // 返回登录界面
    onClickLeft() {
      this.$router.push('/login')
    },
    validator() {
      // 验证密码是否一致
      return this.password1 === this.password2
    }
  }
}
</script>

<style lang="less" scoped>
h1 {
  text-align: center;
  color: #3196fa;
  font-size: 24px;
}

a {
  font-size: 12px;
}
::v-deep {
  .van-nav-bar__content {
    background-color: #3196fa;
  }
  .van-nav-bar__title {
    color: #fff;
  }
  .van-icon.van-icon-arrow-left.van-nav-bar__arrow {
    color: #fff;
  }
}
</style>
